#include "model/UserModel.h"
#include "ServerContext.h"

UserModel::UserModel(const char* db_pool_name,const char* cache_pool_name){
    ctx = ServerContext::getInstance();
    dbpool = static_cast<CDBPool*>(ctx->getContext(db_pool_name));
    cpool = static_cast<CacheConnectionPool*>(ctx->getContext(cache_pool_name));
}

UserModel::~UserModel(){

}

int UserModel::userIsExist(const char* user_name) {
    char sql[512];
    memset(sql,0,sizeof(sql));

    sprintf(sql,"select 1 from tb_app_user where username='%s' ",user_name);

    //智能指针，自动将数据库连接返回连接池
    std::shared_ptr<CDBConn> connPtr(dbpool->GetDBConn(),[=](CDBConn* conn){
        dbpool->RelDBConn(conn);
    });

    std::shared_ptr<CResultSet> result(connPtr->ExecuteQuery(sql));

    if(result->GetResultCount() == 0) {
        return 0;
    }

    return 1;
}

int UserModel::addUser(User* user) {
    char sql[512];
    memset(sql,0,sizeof(sql));
    sprintf(sql,"insert into tb_app_user(username,password,reg_time,exp_time,qq,email) "
                "values('%s','%s',NOW(),date_add(NOW(),interval 7*24 hour),'%s','%s')",
            user->getusername().c_str(),user->getpassword().c_str(),user->getqq().c_str(),user->getemail().c_str());

    std::shared_ptr<CDBConn> connPtr(dbpool->GetDBConn(),[=](CDBConn* conn){
        dbpool->RelDBConn(conn);
    });

    return connPtr->ExecuteUpdate(sql);
}

/**
 * @brief 根据用户名查询用户
 * @param username 用户名
 * @return 查询成功返回用户对象，失败返回NULL
 */
bool UserModel::getUser(const char *username,User& user) {
    char sql[512];
    memset(sql,0,sizeof(sql));

    sprintf(sql,"select username,password,reg_time,exp_time,reg_ip,qq,email "
                "from tb_app_user where username='%s' limit 1",username);

    std::shared_ptr<CDBConn> connPtr(dbpool->GetDBConn(),[=](CDBConn* conn){
        dbpool->RelDBConn(conn);
    });

    std::shared_ptr<CResultSet> result(connPtr->ExecuteQuery(sql));
    if(result->Next()) {

        user.setusername(result->GetStdString("username"));
        user.setpassword(result->GetStdString("password"));
        user.setreg_time(result->GetStdString("reg_time"));
        user.setexp_time(result->GetStdString("exp_time"));
        user.setreg_ip(result->GetStdString("reg_ip"));
        user.setqq(result->GetStdString("qq"));
        user.setemail(result->GetStdString("email"));

        return true;
    }

    return false;
}

/**
 * @brief 将token存入缓存
 * @param username 作为key，token 作为value
 * @return 成功返回 true，失败返回false
 */
bool UserModel::setTokenCache(const char* username,const char *token) {
    std::shared_ptr<CacheConnection> cacheConnPtr(cpool->getCacheConnection(),[=](CacheConnection* cacheConn){
        cpool->putCacheConnection(cacheConn);
    });

    return cacheConnPtr->set(username,token);
}
